/*
 * ledEffects.c
 *
 *  Created on: Feb 1, 2020
 *      Author: Yannick
 */
#include "Leds.h"
#include "main.h"

Ledstruct_t led1 = 
{
	0,0,0,LED_1_GPIO_Port,LED_1_Pin
};
Ledstruct_t led2 = 
{
	0,0,0,LED_2_GPIO_Port,LED_2_Pin
};

/**
 * Blinks led x times with period in ms
 * 0 blinks causes led to blink forever.
 * To stop blinking set period and blinks to 0
 */
void blinkLed(Ledstruct_t* led,uint16_t period,uint16_t blinks){
	// Stop blinking
	if(period == 0 && blinks == 0){
		led->blinks = 0;
		led->period = 0;
		HAL_GPIO_WritePin(led->port, led->pin, GPIO_PIN_SET);
	}else{
		led->blinks = (blinks * 2) -1;
		led->period = period;
		led->tick = HAL_GetTick();
		HAL_GPIO_WritePin(led->port, led->pin, GPIO_PIN_RESET);
	}
}



void blinkLed1(uint16_t period,uint16_t blinks){
	blinkLed(&led1, period, blinks);
}
void blinkLed2(uint16_t period,uint16_t blinks){
	blinkLed(&led2, period, blinks);
}

void updateLed(Ledstruct_t* led){
	// If led has an effect (period != 0) and time is up do something
	if(led->period != 0 && HAL_GetTick() > led->tick+led->period){
		if(led->blinks == 0){ // No blinks left. turn off
			HAL_GPIO_WritePin(led->port, led->pin, GPIO_PIN_SET);
			led->period = 0;
		}else{
			led->tick = HAL_GetTick();
			HAL_GPIO_TogglePin(led->port, led->pin);
		}
		// If positive decrement blink counter.
		if(led->blinks > 0 && led->blinks != 0xFFFF){
			led->blinks--;
		}
	}
}

/**
 * Must be called periodically to update the state of LEDs
 */
void updateLeds(){
    static uint32_t led1SetTimeout = 0;
    if(led1.blinks == 0){
        led1SetTimeout++;
    }else {
        led1SetTimeout = 0;
    }
    if(led1SetTimeout > 20){    // 1S之内无信的信号收到，则设置为系统指示灯
        blinkLed1(500,0xFFFF);
    }
	updateLed(&led1);
	updateLed(&led2);
}
